package com.handa.admin.userservice.service.impl;

import com.handa.admin.userservice.common.entity.LoginUser;
import com.handa.admin.userservice.common.security.service.MyTokenService;
import com.handa.admin.userservice.service.LoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    @Resource
    private MyTokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private UserOnlineService userOnlineService;


    @Override
    public LoginUser login(String username, String password) throws Exception {
        Authentication authentication;
        try {
            authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (BadCredentialsException e) {
            throw new BadCredentialsException("用户名密码错误！");
        } catch (InternalAuthenticationServiceException e) {
            throw new Exception(e.getMessage());
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        loginUser.setJwt(tokenService.newToken(loginUser));
        userOnlineService.userLogin(loginUser);
        return loginUser;
    }

}
